#!/bin/bash
# 快速启动Nacos和RocketMQ的便捷脚本

TOOLS_DIR="$HOME/tools"

echo "=========================================="
echo "启动基础设施服务"
echo "=========================================="
echo ""

# 检查是否已安装
if [ ! -d "$TOOLS_DIR/nacos" ]; then
    echo "❌ Nacos未安装，请先运行: ./install-nacos-rocketmq.sh"
    exit 1
fi

if [ ! -d "$TOOLS_DIR/rocketmq" ]; then
    echo "❌ RocketMQ未安装，请先运行: ./install-nacos-rocketmq.sh"
    exit 1
fi

# 检查端口是否被占用
check_port() {
    if lsof -i :$1 &> /dev/null; then
        return 0
    else
        return 1
    fi
}

# 启动Nacos
if check_port 8848; then
    echo "✅ Nacos已在运行（端口8848）"
else
    echo "启动Nacos..."
    osascript -e "tell application \"Terminal\" to do script \"cd '$TOOLS_DIR' && ./start-nacos.sh\"" 2>/dev/null || {
        echo "请手动在新终端执行: $TOOLS_DIR/start-nacos.sh"
    }
    sleep 3
fi

# 启动RocketMQ NameServer
if check_port 9876; then
    echo "✅ RocketMQ NameServer已在运行（端口9876）"
else
    echo "启动RocketMQ NameServer..."
    osascript -e "tell application \"Terminal\" to do script \"cd '$TOOLS_DIR' && ./start-rocketmq-namesrv.sh\"" 2>/dev/null || {
        echo "请手动在新终端执行: $TOOLS_DIR/start-rocketmq-namesrv.sh"
    }
    sleep 3
fi

# 启动RocketMQ Broker
if check_port 10909; then
    echo "✅ RocketMQ Broker已在运行（端口10909）"
else
    echo "启动RocketMQ Broker..."
    osascript -e "tell application \"Terminal\" to do script \"cd '$TOOLS_DIR' && ./start-rocketmq-broker.sh\"" 2>/dev/null || {
        echo "请手动在新终端执行: $TOOLS_DIR/start-rocketmq-broker.sh"
    }
    sleep 3
fi

echo ""
echo "=========================================="
echo "✅ 基础设施服务启动完成"
echo "=========================================="
echo ""
echo "请检查各个终端窗口，确保服务启动成功"
echo ""
echo "验证服务:"
echo "  Nacos: http://localhost:8848/nacos"
echo "  RocketMQ NameServer: 端口9876"
echo "  RocketMQ Broker: 端口10909"
echo ""
echo "等待10秒后检查服务状态..."
sleep 10

echo ""
echo "服务状态检查:"
if check_port 8848; then
    echo "  ✅ Nacos: 运行中"
else
    echo "  ❌ Nacos: 未运行"
fi

if check_port 9876; then
    echo "  ✅ RocketMQ NameServer: 运行中"
else
    echo "  ❌ RocketMQ NameServer: 未运行"
fi

if check_port 10909; then
    echo "  ✅ RocketMQ Broker: 运行中"
else
    echo "  ❌ RocketMQ Broker: 未运行"
fi

echo ""

